#include <stdio.h>
#include "stack_head.h"

// 初始化栈
int stackInit(commandStack_t* pStack) {
    if (pStack == NULL) {
        return -1;
    }
    pStack->top = NULL;
    pStack->size = 0;
    return 0;
}

// 压栈操作
int push_to_stack(commandStack_t* pStack, const char* command) {
    if (pStack == NULL || command == NULL) {
        return -1;
    }

    node_t* newNode = (node_t*)malloc(sizeof(node_t));
    if (newNode == NULL) {
        return -1;  // 内存分配失败
    }

    strncpy(newNode->command, command, sizeof(newNode->command) - 1);
    newNode->command[sizeof(newNode->command) - 1] = '\0';  // 确保字符串结束
    
    // 新节点指向当前栈顶
    newNode->pNext = pStack->top;
    // 更新栈顶指针
    pStack->top = newNode;
    pStack->size++;
    
    return 0;
}

// 出栈操作
int pop_from_stack(commandStack_t* pStack) {
    if (pStack == NULL || isStackEmpty(pStack)) {
        return -1;
    }

    node_t* temp = pStack->top;
    pStack->top = pStack->top->pNext;
    free(temp);
    pStack->size--;
    
    return 0;
}

// 打印栈内容
int printStack(commandStack_t* pStack) {
    if (pStack == NULL || isStackEmpty(pStack)) {
        printf("栈为空!\n");
        return -1;
    }

    node_t* current = pStack->top;
    printf("栈内容 (从顶到底):\n");
    while (current != NULL) {
        printf("%s\n", current->command);
        current = current->pNext;
    }
    printf("栈中元素总数: %d\n", pStack->size);
    
    return 0;
}

// 检查栈是否为空
int isStackEmpty(commandStack_t* pStack) {
    if (pStack == NULL) {
        return 1;
    }
    return (pStack->top == NULL);
}

// 销毁栈
void destroyStack(commandStack_t* pStack) {
    if (pStack == NULL) {
        return;
    }

    while (!isStackEmpty(pStack)) {
        pop_from_stack(pStack);
    }
    pStack->size = 0;
}
